<?php
namespace app\api\controller;
use app\model\User as UserModel;
use app\model\Integral as IntegralModel;
use app\model\Token as TokenModel;
use think\Db;

use think\facade\Cache;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class User extends Base
{
    protected $noCheckToken = ['login','getSms'];


    /**
     * 获取详情
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function read(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }

        $model = new UserModel();
        $data = $model->where('id',$user_id)->find();
        if (!empty($data)) {
            $data['is_vip'] = $data['vip_time'] >= date('Y-m-d') ? 1 : 0;
        }
        return apiResult('2000','获取成功',$data);
    }

    public function getSms($mobile=''){
        if (strlen($mobile) != 11) {
            $this->error('手机号格式错误');    
        }
        
        $code = rand(1000,9999);
        $sms_res = sendSms($mobile,'您的验证码是：'.$code,'得力云');
        if ($sms_res['status'] == 1) {
            // session('sms_'.$mobile,$code);
            Cache::set('sms_'.$mobile, $code, 120);
            return apiResult('2000','发送成功');
        }else{
            return apiResult('5000',$sms_res['msg']);
        }
    }

    public function updateMobile(){
        if (request()->isPost()) {
            $user_id = $this->login_user['user_id'];
            $fields = [
                'must'=>['mobile','verify']
            ];
            $param = paramFilter(request()->param(),$fields);
            if (!empty($param['error_msg'])) {
                return apiResult('5000',$param['error_msg']);
            }

            $mobile = $param['mobile'];
            if (!isMobile($mobile)) {
                return apiResult('5000','手机号格式错误');  
            }
            if (empty($param['verify']) || $param['verify'] != Cache::get('sms_'.$mobile)) {
                return apiResult('5000','验证码错误');  
            }

            $model = new UserModel();
            if ($model->where([
                ['mobile','=',$mobile],
                ['id','<>',$user_id]
            ])->count() > 0) {
                return apiResult('5000','手机号已被占用');  
            }

            $model->where('id',$user_id)->update([
                'mobile'=>$mobile
            ]);
            return apiResult('2000','绑定成功');  
        }
    }

    /**
     * 获取详情
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
//     public function login(){
//         if (request()->isPost() || TRUE) {
//             // 需要先将公钥pkcs1转成pkcs8
//             // openssl目录：C:\Program Files\OpenSSL-Win64
//             // openssl rsa -RSAPublicKey_in -in C:/dev.pem -pubout -out C:/public.pkcs8.pem
//             $publicKey = '-----BEGIN PUBLIC KEY-----
// MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2vKktjV8DvUm5MPYa+d
// I3lobAdPXRUPt+ZmKYcserGTb0h8pPe6zX1RYxhd96g47/MHD7VSmFBIayjnlK/m
// Izxl4KQx+rLEVqS5LejPtIwLvrh0zRj05MqxqDwfAM1YkMvYpbnifeDdQ22uK4TE
// PoKI80z7HW0i7Js0WiPctez79XBj8heRYPtdrkGIGacluubAmnFDQQiHOD8gCKZo
// FzFbFbJmWR5cb679e2U7dHOWQsdpX0zl+nkjtf9ED2fwiDGt6uVK9Z7MLmAvKUuS
// 2XDaCXdnYB0QqrB8e4LrHiBn+SpezksISXE0ToI1Z1K9jP1cQ/3vYjZo87C6fLgu
// NwIDAQAB
// -----END PUBLIC KEY-----';

//             $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjEwMDAwNCwidXNlcm5hbWUiOiJkZXl1biIsImlzX3N1cGVydXNlciI6ZmFsc2UsImV4cCI6MTcwNTkwMjM2OSwiY3VyIjoxNzA1OTAyMDY5LjgyODU1NTN9.C9Z9e3hz58jt979RSOc8y11dHPe28IqcCdm7_XSLRZhdJIP9labpK03qOmd6vHFSrPYP9CniGf3ZyHurKcSmg46kNxQZK1mS_MJMajcKKdwLaLX1OQ-4103m5PwWAxw_kQxMv6dfo_IFI_iZeJ0nTyv-C80RU5L401ajjUU95Pp1wkqq95esnoOEVdIZTUvvzREuFvB64z9VRfFsexeDZDipuF92CstpluURyUHv0R36khW_iXIw_Y4wi2yh6wRiMvjKp2l7iltUKvUctWn1sQTcP5GvchapT9gGgSMvGUn3zD1AdW4TIq6vIwrcWt-RUbOgQd4OXQq4yZHBKAE7tA';
//             // $token = input('token');
//             if (empty($token)) {
//                 return apiResult('5000','请传入token');  
//             }
//             try {
//                 // $decoded = JWT::decode($token, new Key($publicKey, 'RS256'));
//                 // if (empty($decoded)) {
//                 //     return apiResult('5000','token无效'); 
//                 // }
//                 // $decoded = json_decode(json_encode($decoded),true);
//                 $decoded = [
//                     'uid'=>100004,
//                     'username'=>'deyun',
//                 ];
//                 if (empty($decoded['uid'])) {
//                     return apiResult('5000','token无效');
//                 }
//             } catch (\Exception $e) {
//                 // dump($e->getMessage());die;
//                 return apiResult('5000','token无效');
//             }
            
//             $openid = '360_'.$decoded['uid'];
//             $map = [
//                 ['openid','=',$openid]
//             ];
//             $data = Db::name('user')->where($map)->find();
//             if ( empty($data) ) {
//                 $save_data = [
//                     'openid'=>$openid,
//                     'ctime'=>time(),
//                     'login_time'=>time(),
//                     'nickname'=>$decoded['username'],
//                     'source'=>0
//                 ];
//                 $save_data['headimgurl'] = Db::name('config')->where('key','USER_DEFAULT_IMG')->value('value');
//                 $user_id = Db::name('user')->insertGetId($save_data);

//                 // 生成token
//                 $token_data = [
//                     'user_id'=>$user_id,
//                     'access_token'=>uuidCreate(),
//                     'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
//                     'openid'=>$save_data['openid']
//                 ];
//                 if ( !TokenModel::insert($token_data) ) {
//                     return apiResult('5000','token生成失败');
//                 }
//                 return apiResult('2000','登录成功',$token_data);
//             }else{
//                 $user_id = $data['id'];
//                 Db::name('user')->where('id',$user_id)->update(['login_time'=>time()]);
//                 $access_token = TokenModel::where('user_id',$user_id)->value('access_token');
//                 $token_data = [
//                     'user_id'=>$user_id,
//                     'access_token'=>empty($access_token)?uuidCreate():$access_token,
//                     'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
//                     'is_first'=>0,
//                     'openid'=>$data['openid']
//                 ];
//                 TokenModel::where('user_id',$user_id)->delete();
//                 if ( TokenModel::insert($token_data) ) {
//                     return apiResult('2000','登录成功',$token_data);
//                 }else{
//                     return apiResult('5000','登录异常');
//                 }
//             }
//         }
//     }

    public function login(){
        Db::name('test')->insert(['content'=>'----_REQUEST--------JSON-------']);
        $apiRes = $_REQUEST;
        Db::name('test')->insert(['content'=>'----_REQUEST-----'.json_encode($apiRes)]);
        $data_string = file_get_contents('php://input');
        Db::name('test')->insert(['content'=>'----_JSON-----'.$data_string]);


        if (request()->isPost() || TRUE) {
            // 密钥分量（这里用静态数据模拟，实际中应该是从某处获取的）  
            $key_part1 = hex2bin('38A971F90BB90EC886337A9F05E62D45'); // 示例数据，确保是16字节  
            $key_part2 = hex2bin('8B4BD8CF072978CC1FF8FE111B223039');  
            $key_part3 = hex2bin('51F68015C3CCFBE26AF98E163DA24670');  
              
            // 合并密钥分量  
            $key = '';  
            for ($i = 0; $i < strlen($key_part1); $i++) {  
                $key .= chr(ord($key_part1[$i]) ^ ord($key_part2[$i]) ^ ord($key_part3[$i]));  
            }  

            // 密文，密钥和IV
            // $cipherData = 'c46c148f7a1e6bc141ff7d79637bb4602f119aa0693e5a4ad00eb55210bfacf690d8bd97bbecefb5edea3556038c8af95e8b6c28871901c373c8b0741fad65c498efdfdaf5d12800b5c8de9e0ac5335e53d94d0276fb7c5fdc1655c0b667bc66d194aaa1f1e95e10d1a89d4bd91bc4244ad5ad6647e5c62f58df3c10ed914677b0a7bfba197e635323a7e6f1a669763d6d2cbede0d6aeb69d09d04f86037576a5df95bac5e9ed97fc4c59eef04b6ec406bbd88db49ca7fd6a808075d7c4eee5a';
            $cipherData = input('token');
            if (empty($cipherData)) {
                return apiResult('5000','登录失败：无登录信息');
            }
            Db::name('test')->insert(['content'=>'---token---:'.$cipherData]);
            $cipherData = hex2bin($cipherData);

            $iv = str_repeat("\0", 32); // SM4的块大小为128位或16字节
            // 设置加密算法为SM4-CBC
            $method = "sm4-cbc";

            // 检查密钥长度
            if (strlen($key) !== 16) {
                return apiResult('5000','登录失败：无效key');
            }

            // 解密数据
            $decryptedData = @openssl_decrypt($cipherData, $method, $key, OPENSSL_RAW_DATA, $iv);
            if ($decryptedData === false) {
                // $errorCode = openssl_errno();
                $errorMessage = openssl_error_string();
                return apiResult('5000','登录失败，'.$errorMessage);
            }
            $decoded = json_decode($decryptedData,true);

            $openid = $decoded['epassccid'];
            $map = [
                ['openid','=',$openid]
            ];
            $data = Db::name('user')->where($map)->find();
            if ( empty($data) ) {
                $save_data = [
                    'openid'=>$openid,
                    'ctime'=>time(),
                    'login_time'=>time(),
                    'nickname'=>$decoded['groupNameCN'],
                    'source'=>0
                ];
                $save_data['headimgurl'] = Db::name('config')->where('key','USER_DEFAULT_IMG')->value('value');
                $user_id = Db::name('user')->insertGetId($save_data);

                // 生成token
                $token_data = [
                    'user_id'=>$user_id,
                    'access_token'=>uuidCreate(),
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'openid'=>$save_data['openid']
                ];
                if ( !TokenModel::insert($token_data) ) {
                    return apiResult('5000','token生成失败');
                }
                return apiResult('2000','登录成功',$token_data);
            }else{
                $user_id = $data['id'];
                Db::name('user')->where('id',$user_id)->update(['login_time'=>time()]);
                $access_token = TokenModel::where('user_id',$user_id)->value('access_token');
                $token_data = [
                    'user_id'=>$user_id,
                    'access_token'=>empty($access_token)?uuidCreate():$access_token,
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'is_first'=>0,
                    'openid'=>$data['openid']
                ];
                TokenModel::where('user_id',$user_id)->delete();
                if ( TokenModel::insert($token_data) ) {
                    return apiResult('2000','登录成功',$token_data);
                }else{
                    return apiResult('5000','登录异常');
                }
            }
        }
    }

    // 账号密码登录
    public function alogin(){
        $fields = [
            'must'=>['mobile','verify']
        ];
        $param = paramFilter(request()->param(),$fields);
        if (!empty($param['error_msg'])) {
            return apiResult('5000',$param['error_msg']);
        }

        $mobile = $param['mobile'];
        if (!isMobile($mobile)) {
            return apiResult('5000','手机号格式错误');  
        }
        if (empty($param['verify']) || $param['verify'] != Cache::get('sms_'.$mobile)) {
            return apiResult('5000','验证码错误');  
        }

        $uinfo = UserModel::where('mobile',$mobile)->find();
        if (empty($uinfo)) {
            return apiResult('5000','用户不存在');  
        }

        Db::startTrans();
        try{
            // 生成token
            $token_data = [
                'user_id'=>$uinfo['id'],
                'access_token'=>uuidCreate(),
                'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                'openid'=>$uinfo['openid']
            ];
            TokenModel::where('user_id',$uinfo['id'])->delete();
            if ( !TokenModel::insert($token_data) ) {
                throw new \Exception("token生成失败");
            }
            Db::commit();
            return apiResult('2000','登录成功',$token_data);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

  

    /**
     * 更新手机号码
     * @Author   cch
     * @DateTime 2020-06-15T11:20:42+0800
     * @param    [type]                   $id           [description]
     * @param    [type]                   $encrypted_data [description]
     * @param    [type]                   $iv             [description]
     * @return   [type]                                   [description]
     */
    public function updateWxUserInfo(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'must'=>['iv','encrypted_data'],
            'nomust'=>['code']
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }

        $model = new UserModel();
        $config = config('config.wxparam');
        if (!empty($params['code'])) {
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$params['code'].'&grant_type=authorization_code';
            $user_code = file_get_contents($url); //获取session_key 跟openid 
            $user_code = json_decode($user_code,true);
            if (!empty($user_code['openid'])) {
                $token_data = [
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'session_key'=>$user_code['session_key'],
                    'is_first'=>0
                ];
                if ( !TokenModel::where('user_id',$user_id)->update($token_data) ) {
                    return apiResult('5000','更新session_key异常');
                }
            }
        }

        $session_key = TokenModel::where('user_id',$user_id)->order('expiry_time','desc')->value('session_key');
        $result = xcxDecryptData($session_key,$params['encrypted_data'],$params['iv']);
        if ($result['status'] == 0) {
            return apiResult('2000',$result['msg']);
        }
        if (!empty($result['data'])) {
            $data = $model->where('id',$user_id)->find();
            
            $save_data = [
                'nickname'=>$result['data']['nickName'],
                'headimgurl'=>$result['data']['avatarUrl']
            ];
            if ( $model->where('id',$user_id)->update($save_data) !== false ) {
                return apiResult('2000','授权成功');
            }else{
                return apiResult('5000','更新失败，请重试');
            }
        }else{
            return apiResult('5000','获取数据失败');
        }
    }

    public function updateWxMobile(){
        $openid = $this->login_user['openid'];
        if (empty($openid)) {
            exception('请登录后操作',400);
        }

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        // dump($param);die;

        // $param = '{"code":"0a37TFFa1KeWAG0lQMGa16L2qg17TFFx","iv":"0OS8+4oVjUM98UE0eI6kNg==","encrypted_data":"mtl/9bo3Zxyp0SIdW+kJgWIf9oYVm9yMZ+aeWyIyujCYblqzZ7mnLx6pOhm5PbCoelpu4ntzJk9nnxtmRuT5wjUNDx+tAm/I/7r8WOU5n67xe3Q8IjWhaxbt4RPXfAeGBTm6y57/0obujnMsCqRqbP4av2gVrhhuz0gwShIguFMfuXYwjphrj+X1S18JgUSRFii/LRVc2ipZcKHCYTkgAg=="}';
        // $param = json_decode($param,true);


        $fields = [
            'must'=>['iv','encrypted_data'],
            'nomust'=>['code']
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }
        $model = new UserModel();
        $config = config('config.wxparam');
        if (!empty($params['code'])) {
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$params['code'].'&grant_type=authorization_code';
            $user_code = file_get_contents($url); //获取session_key 跟openid
            $user_code = json_decode($user_code,true);
            if (!empty($user_code['openid'])) {
                $token_data = [
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'session_key'=>$user_code['session_key'],
                    'is_first'=>0
                ];
                if ( !TokenModel::where('openid',$openid)->update($token_data) ) {
                    return apiResult('5000','更新session_key异常');
                }
            }
        }

        $session_key = TokenModel::where('openid',$openid)->order('expiry_time','desc')->value('session_key');
        $result = xcxDecryptData($session_key,$params['encrypted_data'],$params['iv']);
        if ($result['status'] == 0) {
            return apiResult('5000',$result['msg']);
        }
        $mobile = $result['data']['phoneNumber'];
        return apiResult('2000','授权成功',$mobile);
    }

    /**
     * 保存
     * @Author   cch
     * @DateTime 2020-05-26T17:22:32+0800
     * @return   [type]                   [description]
     */
    public function update(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'nomust'=>['headimgurl','nickname','remark','email','company']
        ];
        $save_data = paramFilter($param,$fields);
        if (empty($save_data)) {
            return apiResult('5000','无任何更改');
        }

        $model = new UserModel();
        $data = $model->where('id',$user_id)->find();

        if ( $model->where('id',$user_id)->update($save_data) !== false ) {
            return apiResult('2000','更新成功');
        }else{
            return apiResult('2000','提交成功',$id);
        }
    }

    public function statistics(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }
        $start_time = input('start_time',date('Y-m-d'));
        $start_time = strtotime($start_time.' 00:00:00');
        $end_time = input('end_time',date('Y-m-d'));
        $end_time = strtotime($end_time.' 23:59:59');

        $data = [];
        // 累计查勘量
        $data['total_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','between',[$start_time,$end_time]]
        ])->count();
        // 今日查勘量
        $data['attach_num'] = Db::name('order_attach')->where([
            ['user_id','=',$user_id],
            ['ctime','between',[$start_time,$end_time]]
        ])->count();
        

        return apiResult('2000','获取成功',$data);
    }

    public function statistics2(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }
        $data = [];
        $curdate = strtotime(date('Y-m-d'));
        $curmoth = strtotime(date('Y-m-01'));
        // 今日查勘量
        $data['td_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','>=',$curdate]
        ])->count();
        // 昨日查勘量
        $data['yd_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','between',[strtotime('-1 days',$curdate),$curdate]]
        ])->count();
        // 本月查勘量
        $data['month_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','>=',$curmoth]
        ])->count();
        // 累计查勘量
        $data['total_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
        ])->count();

        return apiResult('2000','获取成功',$data);
    }



}
